package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.IcEmvInfo;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.RedpUtil;
import cc.rengu.redp.common.utils.SortUtil;
import cc.rengu.redp.bizimpl.upmp.dao.IcPubKeyInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.IcPubKeyInfo;
import cc.rengu.redp.bizimpl.upmp.domain.IcPubKeyInfoBean;
import cc.rengu.redp.bizimpl.upmp.service.IcPubKeyInfoService;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author LiuYuLiang.LL
 */
@Service
@DS("upmp")
public class IcPubKeyInfoServiceImpl extends ServiceImpl<IcPubKeyInfoMapper, IcPubKeyInfo> implements IcPubKeyInfoService {
    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Override
    public IPage<IcPubKeyInfo> findByPage(QueryRequest request, IcPubKeyInfo info) {
        try {
            LambdaQueryWrapper<IcPubKeyInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(info.getInstId())) {
                queryWrapper.eq(IcPubKeyInfo::getInstId, info.getInstId());
            } else {
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                queryWrapper.eq(IcPubKeyInfo::getInstId, user.getInstId());
            }
            if (StringUtils.isNotBlank(info.getParaVal())) {
                queryWrapper.likeRight(IcPubKeyInfo::getParaVal, info.getParaVal());
            }

            queryWrapper.likeRight(IcPubKeyInfo::getUsageKey, "1");
            queryWrapper.orderByDesc(IcPubKeyInfo::getCreateTime);
            Page<IcPubKeyInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }

    @Override
    @Transactional
    public void create(IcPubKeyInfo entity) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);

        entity.setInstId(user.getInstId());
        entity.setStatus(BusinessContainer.status_00);//状态
        entity.setAuditStatus(BusinessContainer.status_02);
        entity.setOprId(user.getId());
        entity.setCrtOrgId(user.getOrgCode());
        entity.setCreateTime(lastUpddt);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        String rid = "9F0605" + entity.getTgzbs();
        String gysy = "9F2201" + entity.getGysy();
        String hxsfbs = "DF0601" + entity.getHxsfbs();
        String gysfbs = "DF0701" + entity.getGysfbs();
        int lenth = (entity.getGym().length()) / 2;
        String len = Integer.toHexString(lenth);
        if (Integer.parseInt(len) < 10) {
            len = "0" + len;
        }
        String gym = "DF0281" + len + entity.getGym();
        String gyzs = "DF0401" + entity.getGyzs();
        int lenth1 = (entity.getGyxyz().length()) / 2;
        String len1 = Integer.toHexString(lenth1).toString();
        String gyxyz = "DF03" + len1 + entity.getGyxyz();
        String rq = entity.getGxyxq().replaceAll("-", "").substring(0, 8);
        String yxq = "";
        for (int i = 0; i < rq.length(); i++) {
            yxq += "3" + rq.charAt(i);
        }
        String gxyxq = "DF0508" + yxq;
        entity.setParaId(entity.getTgzbs());//AID
        entity.setParaVal(rid + gysy + gxyxq + hxsfbs + gysfbs + gym + gyzs + gyxyz);//参数值
          entity.setUsageKey("1");//参数类型
        entity.setParaIdx(entity.getGysy());//参数索引
        entity.setParaOrg("CA");//卡组织标识
        entity.setParaSta("I");//状态
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());//长度
        this.baseMapper.insert(entity);
    }

    @Override
    @Transactional
    public void update(IcPubKeyInfo entity) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        // 修改
        entity.setAuditStatus(BusinessContainer.status_42);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        String rid = "9F0605" + entity.getTgzbs();
        String gysy = "9F2201" + entity.getGysy();
        String hxsfbs = "DF0601" + entity.getHxsfbs();
        String gysfbs = "DF0701" + entity.getGysfbs();
        int lenth = (entity.getGym().length()) / 2;
        String len = Integer.toHexString(lenth);
        if (Integer.parseInt(len) < 10) {
            len = "0" + len;
        }
        String gym = "DF0281" + len + entity.getGym();
        String gyzs = "DF0401" + entity.getGyzs();
        int lenth1 = (entity.getGyxyz().length()) / 2;
        String len1 = Integer.toHexString(lenth1).toString();
        String gyxyz = "DF03" + len1 + entity.getGyxyz();
        String rq = entity.getGxyxq().replaceAll("-", "").substring(0, 8);
        String yxq = "";
        for (int i = 0; i < rq.length(); i++) {
            yxq += "3" + rq.charAt(i);
        }
        String gxyxq = "DF0508" + yxq;
        entity.setParaId(entity.getTgzbs());//AID
        entity.setParaVal(rid + gysy + gxyxq + hxsfbs + gysfbs + gym + gyzs + gyxyz);//参数值
        entity.setUsageKey("1");//参数类型
        entity.setParaIdx(entity.getGysy());//参数索引
        entity.setParaOrg("CA");//卡组织标识
        entity.setParaSta("I");//状态
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());//长度
        this.baseMapper.updateById(entity);
    }

    @Override
    @Transactional
    public void newCreate(IcPubKeyInfo entity) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        entity.setInstId(user.getInstId());
        entity.setStatus(BusinessContainer.data_sta_01);
        entity.setAuditStatus(BusinessContainer.status_02);
        entity.setOprId(user.getId());
        entity.setCrtOrgId(user.getOrgCode());
        entity.setCreateTime(lastUpddt);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        entity.setParaId(entity.getTgzbs());//AID
        IcPubKeyInfoBean icpubkeyinfobean = new IcPubKeyInfoBean();
        icpubkeyinfobean.setEFFC_DATE(entity.getGxyxq());//有效期
        icpubkeyinfobean.setHSID(entity.getHxsfbs());//哈希算法标识
        icpubkeyinfobean.setPKID(entity.getGysfbs());//公钥算法标识
        icpubkeyinfobean.setPK_MOD(entity.getGym());//公钥模
        icpubkeyinfobean.setPK_EXP(entity.getGyzs());//公钥指数
        icpubkeyinfobean.setCHECK_VALUE(entity.getGyxyz());//公钥校验值
        entity.setParaVal(JSON.toJSONString(icpubkeyinfobean));//参数值
        entity.setUsageKey("1");//参数类型
        entity.setParaOrg("CA");//卡组织标识
        entity.setParaSta("I");//状态
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());//长度
        this.baseMapper.insert(entity);
    }

    @Override
    @Transactional
    public void newUpdate(IcPubKeyInfo entity) {
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        // 修改
        entity.setAuditStatus(BusinessContainer.status_42);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        entity.setParaId(entity.getTgzbs());//AID
        IcPubKeyInfoBean icpubkeyinfobean = new IcPubKeyInfoBean();
        icpubkeyinfobean.setEFFC_DATE(entity.getGxyxq());//有效期
        icpubkeyinfobean.setHSID(entity.getHxsfbs());//哈希算法标识
        icpubkeyinfobean.setPKID(entity.getGysfbs());//公钥算法标识
        icpubkeyinfobean.setPK_MOD(entity.getGym());//公钥模
        icpubkeyinfobean.setPK_EXP(entity.getGyzs());//公钥指数
        icpubkeyinfobean.setCHECK_VALUE(entity.getGyxyz());//公钥校验值
        entity.setParaVal(JSON.toJSONString(icpubkeyinfobean));//参数值
        entity.setUsageKey("1");//参数类型
        entity.setParaOrg("CA");//卡组织标识
        entity.setParaSta("I");//状态
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());//长度
        this.baseMapper.updateById(entity);
    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(list);
    }

    @Override
    public void addIcPubKey(IcPubKeyInfo icEmvInfo) {
        saveData(icEmvInfo);
    }

    @Override
    public void updIcPubKey(IcPubKeyInfo icEmvInfo) {
        saveData(icEmvInfo);
    }

    private void saveData(IcPubKeyInfo entity) {
        String optFlag = entity.getOptFlag();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");

        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();

//		String time2 = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
        entity.setUsageKey("1");//参数类型
        entity.setParaOrg("CA");//卡组织标识
        entity.setParaLen(((Integer) entity.getParaVal().length()).toString());//长度
        if ("add".equals(optFlag)) {
            entity.setParaSta("I");//状态
            entity.setCrtOrgId(user.getOrgCode());//创建机构
            entity.setOprId(user.getId());//创建人
            entity.setStatus(BizDataStatusEnum.STATUS_NORMAL.getType());//状态
            entity.setCreateTime(lastUpddt);//创建时间戳
            entity.setLastOprId(user.getId());//最后修改人
            entity.setLastUpdateTime(lastUpddt);//最后修改时间戳
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
            this.save(entity);
        } else if ("upd".equals(optFlag)) {
            entity.setParaSta("U");//状态
            entity.setLastOprId(user.getId());//最后修改人
            entity.setLastUpdateTime(lastUpddt);//最后修改时间戳
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
            baseMapper.updateById(entity);
        }
    }


}
